<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>项目打分</span>
        </div>
      </template>

      <span style="font-size: 15px"> 年份：</span>
      <el-select v-model="searchForm.year" placeholder="Select" style="width: 140px" @change="searchOrder">
        <el-option v-for="item in years" :key="item.year" :value="item.year" />
      </el-select>

      <span style="font-size: 15px; margin-left: 20px"> 月份：</span>
      <el-select v-model="searchForm.month" placeholder="Select" style="width: 80px" @change="searchOrder">
        <el-option v-for="item in 12" :key="item" :value="item" :label="`${item}月`" />
      </el-select>


      <el-button type="primary" style="float:right;margin-right:10px" @click="goPerson">
        查看人员工分<el-icon class="el-icon--right">
          <Search />
        </el-icon>
      </el-button>

      <el-button type="success" style="float:right;margin-right:10px" @click="goGood">
        查看当月好稿<el-icon class="el-icon--right">
          <List />
        </el-icon>
      </el-button>

      <el-tabs class="el-tab" v-loading="loading" element-loading-text="加载中..." :element-loading-spinner="svg"
        element-loading-svg-view-box="-10, -10, 50, 50" element-loading-background="rgba(255, 255, 255, 0.8)">
        <el-tab-pane label="编辑">
          <!-- 成员按钮 -->
          <div class="members">
            <el-button @click="clearFilterBianji" v-show="membersBianji.length != 0"
              :class="{ active: selectedMember === '' }">显示全部</el-button>
            <el-button v-for="member in membersBianji" :key="member" @click="filterByMemberBianji(member)"
              style="margin-right: 10px" :class="{ active: selectedMember === member }">
              {{ member }}
            </el-button>
          </div>
          <el-table :data="tableDataBianji" style="width: 100%; margin-top: 20px"
            :row-class-name="tableBianjiRowClassName" :row-click-expand="true" class="my-table">
            <el-table-column type="expand">
              <template #default="scope">
                <div v-if="Array.isArray(scope.row.files)" style="margin-left: 50px;">
                  <div v-if="scope.row.files[0].id != null">
                    <div class="files-wrapper">
                      <template v-for="(item, index) in scope.row.files">
                        <div class="file-container" @mouseover="hover = `${scope.$index}-${index}`"
                          @mouseleave="hover = null">
                          <el-image v-if="tool.isImage(item.url)" :src="`${baseURL}/${item.url}`" :zoom-rate="1.2"
                            :max-scale="7" :min-scale="0.2" :initial-index="index" :preview-teleported="true"
                            :preview-src-list="scope.row.files.filter(file => tool.isImage(file.url)).map(file => `${baseURL}/${file.url}`)
                              " fit="cover" class="image" @load="onLoadImage" />
                          <video v-else-if="tool.isVideo(item.url)" :src="`${baseURL}/${item.url}`" controls class="video"
                            preload="metadata"></video>
                          <a :href="`${baseURL}/${item.url}`" class="file-download" target="_blank" v-else>
                            <div class="doc">
                              <span>{{ item.original_name }}</span>
                            </div>
                          </a>
                          <el-button type="danger" :icon="Delete" circle @click="delFile(scope.row.id, item.id)"
                            v-show="hover === `${scope.$index}-${index}`"
                            style="position: absolute;right:20px;top:10px;width:30px;height:30px" />
                        </div>
                      </template>
                    </div>
                  </div>
                  <div v-else style="margin: 10px 10px; color: gray">
                    该项目没上传文件
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="product_name" label="项目名称" width="250" />
            <el-table-column prop="member" label="人员">
              <template #default="scope">
                <el-tag class="ml-2">{{ scope.row.member }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="department_name" label="部门" />
            <el-table-column prop="remark" label="备注" width="300">
              <template #default="scope">
                <span v-html="formatRemark(scope.row.remark)"></span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width=90>
              <template #default="scope">
                <el-button :type="scope.row.my_score ? 'info' : 'primary'" @click="handleScore(scope.row, '编辑')">{{
                  scope.row.my_score ? '修改' : '打分'
                }}</el-button>
              </template>
            </el-table-column>
            <el-table-column label="我的打分">
              <template #default="scope">
                <div style="color:#67C23A;font-weight:bold;font-size:20px">{{ scope.row.my_score }}</div>
                <div style="font-size:13px;color:gray">{{ scope.row.my_score_remark }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="other_score" label="参考打分">
              <template #default="scope">
                <div v-for="(score, index) in scope.row.other_score" :key="index">{{ score }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="isGood" label="选好稿">
              <template #default="scope">
                <el-button :type="scope.row.isGood ? 'danger' : ''" @click="handleGoodPaper(scope.row, '编辑')">
                  <template v-if="scope.row.isGood">
                    <el-icon>
                      <StarFilled />
                    </el-icon>
                    <div style="padding-left:3px">{{ scope.row.goodScore }}</div>
                  </template>
                  <template v-else>
                    选为好稿
                  </template>
                </el-button>
                <div style="padding:3px">{{ scope.row.goodRemark }}</div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="设计">
          <!-- 成员按钮 -->
          <div class="members">
            <el-button @click="clearFilterSheji" v-show="membersSheji.length != 0"
              :class="{ active: selectedMember === '' }">显示全部</el-button>
            <el-button v-for="member in membersSheji" :key="member" @click="filterByMemberSheji(member)"
              style="margin-right: 10px" :class="{ active: selectedMember === member }">
              {{ member }}
            </el-button>
          </div>
          <el-table :data="tableDataSheji" style="width: 100%; margin-top: 20px" :row-class-name="tableShejiRowClassName"
            :row-click-expand="true" class="my-table">
            <el-table-column type="expand">
              <template #default="scope">
                <div v-if="Array.isArray(scope.row.files)" style="margin-left: 50px;">
                  <div v-if="scope.row.files[0].id != null">
                    <div class="files-wrapper">
                      <template v-for="(item, index) in scope.row.files">
                        <div class="file-container" @mouseover="hover = `${scope.$index}-${index}`"
                          @mouseleave="hover = null">
                          <el-image v-if="tool.isImage(item.url)" :src="`${baseURL}/${item.url}`" :zoom-rate="1.2"
                            :max-scale="7" :min-scale="0.2" :initial-index="index" :preview-teleported="true"
                            :preview-src-list="scope.row.files.filter(file => tool.isImage(file.url)).map(file => `${baseURL}/${file.url}`)
                              " fit="cover" class="image" @load="onLoadImage" />
                          <video v-else-if="tool.isVideo(item.url)" :src="`${baseURL}/${item.url}`" controls class="video"
                            preload="metadata"></video>
                          <a :href="`${baseURL}/${item.url}`" class="file-download" target="_blank" v-else>
                            <div class="doc">
                              <span>{{ item.original_name }}</span>
                            </div>
                          </a>
                          <el-button type="danger" :icon="Delete" circle @click="delFile(scope.row.id, item.id)"
                            v-show="hover === `${scope.$index}-${index}`"
                            style="position: absolute;right:20px;top:10px;width:30px;height:30px" />
                        </div>
                      </template>
                    </div>
                  </div>
                  <div v-else style="margin: 10px 10px; color: gray">
                    该项目没上传文件
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="product_name" label="项目名称" width="250">
              <template #default="{ row }">
                <span v-if="row.displayName" v-html="row.displayName"></span>
                <span v-else>{{ row.product_name }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="member" label="人员">
              <template #default="scope">
                <el-tag class="ml-2">{{ scope.row.member }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="department_name" label="部门" />
            <el-table-column prop="remark" label="备注" width="300">
              <template #default="scope">
                <span v-html="formatRemark(scope.row.remark)"></span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width=90>
              <template #default="scope">
                <el-button :type="scope.row.my_score ? 'info' : 'primary'" @click="handleScore(scope.row, '设计')">{{
                  scope.row.my_score ? '修改' : '打分'
                }}</el-button>
              </template>
            </el-table-column>
            <el-table-column label="我的打分">
              <template #default="scope">
                <div style="color:#67C23A;font-weight:bold;font-size:20px">{{ scope.row.my_score }}</div>
                <div style="font-size:13px;color:gray">{{ scope.row.my_score_remark }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="other_score" label="参考打分">
              <template #default="scope">
                <div v-for="(score, index) in scope.row.other_score" :key="index">{{ score }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="isGood" label="选好稿">
              <template #default="scope">
                <el-button :type="scope.row.isGood ? 'danger' : ''" @click="handleGoodPaper(scope.row, '设计')">
                  <template v-if="scope.row.isGood">
                    <el-icon>
                      <StarFilled />
                    </el-icon>
                    <div style="padding-left:3px">{{ scope.row.goodScore }}</div>
                  </template>
                  <template v-else>
                    选为好稿
                  </template>
                </el-button>
                <div style="padding:3px">{{ scope.row.goodRemark }}</div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="技术">
          <!-- 成员按钮 -->
          <div class="members">
            <el-button @click="clearFilterJishu" v-show="membersJishu.length != 0"
              :class="{ active: selectedMember === '' }">显示全部</el-button>
            <el-button v-for="member in membersJishu" :key="member" @click="filterByMemberJishu(member)"
              style="margin-right: 10px" :class="{ active: selectedMember === member }">
              {{ member }}
            </el-button>
          </div>
          <el-table :data="tableDataJishu" style="width: 100%; margin-top: 20px" :row-class-name="tableJishuRowClassName"
            :row-click-expand="true" class="my-table">
            <el-table-column type="expand">
              <template #default="scope">
                <div v-if="Array.isArray(scope.row.files)" style="margin-left: 50px;">
                  <div v-if="scope.row.files[0].id != null">
                    <div class="files-wrapper">
                      <template v-for="(item, index) in scope.row.files">
                        <div class="file-container" @mouseover="hover = `${scope.$index}-${index}`"
                          @mouseleave="hover = null">
                          <el-image v-if="tool.isImage(item.url)" :src="`${baseURL}/${item.url}`" :zoom-rate="1.2"
                            :max-scale="7" :min-scale="0.2" :initial-index="index" :preview-teleported="true"
                            :preview-src-list="scope.row.files.filter(file => tool.isImage(file.url)).map(file => `${baseURL}/${file.url}`)
                              " fit="cover" class="image" @load="onLoadImage" />
                          <video v-else-if="tool.isVideo(item.url)" :src="`${baseURL}/${item.url}`" controls class="video"
                            preload="metadata"></video>
                          <a :href="`${baseURL}/${item.url}`" class="file-download" target="_blank" v-else>
                            <div class="doc">
                              <span>{{ item.original_name }}</span>
                            </div>
                          </a>
                          <el-button type="danger" :icon="Delete" circle @click="delFile(scope.row.id, item.id)"
                            v-show="hover === `${scope.$index}-${index}`"
                            style="position: absolute;right:20px;top:10px;width:30px;height:30px" />
                        </div>
                      </template>
                    </div>
                  </div>
                  <div v-else style="margin: 10px 10px; color: gray">
                    该项目没上传文件
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="product_name" label="项目名称" width="250" />
            <el-table-column prop="member" label="人员">
              <template #default="scope">
                <el-tag class="ml-2">{{ scope.row.member }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="department_name" label="部门" />
            <el-table-column prop="remark" label="备注" width="300">
              <template #default="scope">
                <span v-html="formatRemark(scope.row.remark)"></span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width=90>
              <template #default="scope">
                <el-button :type="scope.row.my_score ? 'info' : 'primary'" @click="handleScore(scope.row, '技术')">{{
                  scope.row.my_score ? '修改' : '打分'
                }}</el-button>
              </template>
            </el-table-column>
            <el-table-column label="我的打分">
              <template #default="scope">
                <div style="color:#67C23A;font-weight:bold;font-size:20px">{{ scope.row.my_score }}</div>
                <div style="font-size:13px;color:gray">{{ scope.row.my_score_remark }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="other_score" label="参考打分">
              <template #default="scope">
                <div v-for="(score, index) in scope.row.other_score" :key="index">{{ score }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="isGood" label="选好稿">
              <template #default="scope">
                <el-button :type="scope.row.isGood ? 'danger' : ''" @click="handleGoodPaper(scope.row, '技术')">
                  <template v-if="scope.row.isGood">
                    <el-icon>
                      <StarFilled />
                    </el-icon>
                    <div style="padding-left:3px">{{ scope.row.goodScore }}</div>
                  </template>
                  <template v-else>
                    选为好稿
                  </template>
                </el-button>
                <div style="padding:3px">{{ scope.row.goodRemark }}</div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <el-dialog :title="currentData.title" v-model="dialogVisible" width="600" @close="handleClose" align-center>
        <div><span style="margin-right: 10px;">工分：</span><el-input v-model="score" placeholder="请输入工分" ref="scoreInput"
            style="width: 150px;margin-bottom:10px" @input="handleInput"></el-input></div>
        <div><span style="margin-right: 10px;vertical-align: top;">备注：</span><el-input v-model="score_remark"
            placeholder="这里写备注，可不填" :rows="4" type="textarea" style="width: 300px;"></el-input></div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleConfirm">确 定</el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog :title="currentGoodData.title" v-model="goodDialogVisible" width="600" @close="handleGoodClose"
        align-center>
        <div style="margin-bottom:10px"><span style="margin-right: 10px;vertical-align: top;">得分：</span><el-input
            v-model="currentGoodData.goodScore" ref="goodScoreInput" placeholder=""  type="text"
            style="width: 100px;"></el-input></div>
        <div><span style="margin-right: 10px;vertical-align: top;">理由：</span><el-input
            v-model="currentGoodData.goodRemark" ref="goodRemarkInput" placeholder="这里写备注，可不填" :rows="4" type="textarea"
            style="width: 300px;"></el-input></div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="goodDialogVisible = false" v-if="!currentGoodData.isGood">取消</el-button>
            <el-button @click="delGood" v-if="currentGoodData.isGood">取消好稿</el-button>
            <el-button type="primary" @click="handleGoodConfirm">确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, nextTick, watch } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import workApi from '../../api/work'
import tool from '../../tools/tool'
import { useRouter } from 'vue-router'
const router = useRouter()
const tableData = ref([])
const tableDataBianji = ref([])
const tableDataSheji = ref([])
const tableDataJishu = ref([])
const dialogVisible = ref(false)
const goodDialogVisible = ref(false)
const years = ref()
const score = ref()
const score_remark = ref()
const selectedMember = ref('') // 当前选中的成员
const membersBianji = ref([])
const membersSheji = ref([])
const membersJishu = ref([])
const originalDataBianji = ref([])
const originalDataSheji = ref([])
const originalDataJishu = ref([])
const loading = ref(false);
const currentData = reactive({
  title: '',
  type: '',
  id: ''
})

const currentGoodData = reactive({
  title: '',
  type: '',
  id: '',
  isGood: '',
  goodRemark: '',
  goodScore:''
})

// 获取全局变量
const baseURL = window.globalConfig.baseURL
const username = sessionStorage.getItem('username')

// 搜索条件
const searchForm = reactive({
  username: username,
  name: '',
  year: '',
  month: '',
})

onMounted(async () => {
  const yearRes = await workApi.getDistinctYears()
  years.value = yearRes.data
  console.log(years.value)
  //默认今年
  const currentYear = new Date().getFullYear()
  searchForm.year = currentYear

  //默认当月
  const currentMonth = new Date().getMonth() + 1
  searchForm.month = currentMonth

  searchOrder()
  initializeTableDataSheji();
})

// 获取数据列表
const searchOrder = async () => {
  loading.value = true;

  try {
    tableData.value = []
    tableDataBianji.value = []
    tableDataSheji.value = []
    tableDataJishu.value = []
    const res = await workApi.getAllListByMonth(searchForm)
    const resData = res.data
    // 创建一个 Map 对象，用于存储相同 id 的数据
    const idMap = new Map()

    // 遍历数据数组，将具有相同 id 的数据的 url 合并到一个数组中
    resData.forEach((item) => {
      const id = item.id;
      if (idMap.has(id)) {
        const filesArray = idMap.get(id).files;
        // 检查是否已经存在相同的 file_id
        const exists = filesArray.some(file => file.id === item.file_id);
        if (!exists) {
          filesArray.push({ id: item.file_id, url: item.url, original_name: item.original_name });
        }
        if (item.scorer !== username) {
          if (item.score != null) {
            const score = `${item.scorer}：${item.score}${item.score_remark ? `(${item.score_remark})` : ''}`;
            idMap.get(id).other_score = idMap.get(id).other_score || [];
            if (!idMap.get(id).other_score.includes(score)) {
              idMap.get(id).other_score.push(score);
            }
          }
        } else {
          idMap.get(id).my_score = item.score
          idMap.get(id).my_score_remark = item.score_remark
        }
      } else {
        idMap.set(id, { ...item, files: [{ id: item.file_id, url: item.url, original_name: item.original_name }] });
        if (item.scorer !== username) {
          if (item.scorer != null) {
            idMap.get(id).other_score = [`${item.scorer}：${item.score}${item.score_remark ? `(${item.score_remark})` : ''}`];
          }
        } else {
          idMap.get(id).my_score = item.score
          idMap.get(id).my_score_remark = item.score_remark
        }
      }
    });

    // 将 Map 对象转换为数组
    const result = Array.from(idMap.values())

    //这里把当月所有好稿都列出来，然后和主列表合并 begin
    const resGood = await workApi.getGoodListByMonth(searchForm)
    const goodList = resGood.data
    result.forEach((item) => {
      item.isGood = false;  // 初始化为 false
      item.goodRemark = '';
      item.goodScore='';
      goodList.forEach((goodItem) => {
        if (goodItem.order_id == item.id && username == goodItem.voter) {
          item.isGood = true
          item.goodRemark = goodItem.remark
          item.goodScore = goodItem.score
        }
      })
    })
    //这里把当月所有好稿都列出来 end

    tableData.value = result



    // 遍历 tableData 中的每个记录
    tableData.value.forEach((item) => {
      if (item.type == "编辑") {
        tableDataBianji.value.push(item)
      }
      if (item.type == "设计") {
        tableDataSheji.value.push(item)
      }
      if (item.type == "技术") {
        tableDataJishu.value.push(item)
      }
    })


    tableDataBianji.value.sort((a, b) => {
      if (a.member < b.member) {
        return -1;
      }
      if (a.member > b.member) {
        return 1;
      }
      return 0;
    });

    tableDataSheji.value.sort((a, b) => {
      if (a.member < b.member) {
        return -1;
      }
      if (a.member > b.member) {
        return 1;
      }
      return 0;
    });

    tableDataJishu.value.sort((a, b) => {
      if (a.member < b.member) {
        return -1;
      }
      if (a.member > b.member) {
        return 1;
      }
      return 0;
    });

    // 初始化成员列表，用于筛选成员
    membersBianji.value = [...new Set(tableDataBianji.value.map(item => item.member))];
    membersSheji.value = [...new Set(tableDataSheji.value.map(item => item.member))];
    membersJishu.value = [...new Set(tableDataJishu.value.map(item => item.member))];
    //复制一个原始的表格
    originalDataBianji.value = [...tableDataBianji.value];
    originalDataSheji.value = [...tableDataSheji.value];
    originalDataJishu.value = [...tableDataJishu.value];
  } catch (error) {
    console.error('数据加载错误:', error);
    ElMessage.error('数据加载失败，请重试');
  } finally {
    loading.value = false;
  }
}

const handleInput = (value) => {
  const newValue = value.replace(/[^\d]/g, ''); // 只保留数字
  score.value = newValue;
}

const handleClose = () => {
  console.log('已取消');
  dialogVisible.value = false;
  score.value = ""
  score_remark.value = ""
}

const handleConfirm = async () => {
  if (!score.value) {
    ElMessage.error('请输入工分');
    return;
  }
  const data = {
    id: currentData.id,
    score: parseInt(score.value),
    score_remark: score_remark.value || '',
    username: username
  };

  const res = await workApi.addScore(data);
  if (res.data.id) {
    ElMessage({
      type: 'success',
      message: `打分成功`,
    });
    // 更新指定数据表中的条目
    const updateScore = (tableData) => {
      const item = tableData.value.find(item => item.id === currentData.id);
      if (item) {
        item.my_score = data.score;
        item.my_score_remark = data.score_remark;
      }
    };

    switch (currentData.type) {
      case '编辑':
        updateScore(tableDataBianji);
        break;
      case '设计':
        updateScore(tableDataSheji);
        break;
      case '技术':
        updateScore(tableDataJishu);
        break;
      default:
        console.warn(`未知的类型: ${currentData.type}`);
    }
    dialogVisible.value = false;
    score.value = ""
    score_remark.value = ""

    //更新剩余分数
    initializeTableDataSheji();
  } else {
    ElMessage({
      type: 'info',
      message: '打分失败',
    });
  }
};

const handleGoodConfirm = async () => {
  const data = {
    id: currentGoodData.id,
    remark: currentGoodData.goodRemark || '(推荐)',
    voter: username,
    score:currentGoodData.goodScore || ''
  };

  const res = await workApi.addGood(data);
  if (res.data.id) {
    ElMessage({
      type: 'success',
      message: `已将${currentGoodData.title}设为好稿`,
    });
    // 更新指定数据表中的条目
    const updateGood = (tableData) => {
      const item = tableData.value.find(item => item.id === currentGoodData.id);
      if (item) {
        item.isGood = true;
        item.goodRemark = data.remark;
        item.goodScore = data.score;
      }
    };

    switch (currentGoodData.type) {
      case '编辑':
        updateGood(tableDataBianji);
        break;
      case '设计':
        updateGood(tableDataSheji);
        break;
      case '技术':
        updateGood(tableDataJishu);
        break;
      default:
        console.warn(`未知的类型: ${currentGoodData.type}`);
    }
    goodDialogVisible.value = false;
    currentGoodData.goodRemark = ""
    currentGoodData.goodScore = ""
  } else {
    ElMessage({
      type: 'info',
      message: '设置失败',
    });
  }
};

//取消好稿
const delGood = async () => {
  const data = {
    id: currentGoodData.id,
    remark: currentGoodData.goodRemark || '',
    voter: username
  };

  const res = await workApi.delGood(data);
  if (res.data.success) {
    ElMessage({
      type: 'success',
      message: `已将${currentGoodData.title}移除好稿`,
    });
    // 更新指定数据表中的条目
    const updateGood = (tableData) => {
      const item = tableData.value.find(item => item.id === currentGoodData.id);
      if (item) {
        item.isGood = false;
        item.goodRemark = '';
        item.goodScore = '';
      }
    };

    switch (currentGoodData.type) {
      case '编辑':
        updateGood(tableDataBianji);
        break;
      case '设计':
        updateGood(tableDataSheji);
        break;
      case '技术':
        updateGood(tableDataJishu);
        break;
      default:
        console.warn(`未知的类型: ${currentGoodData.type}`);
    }
    goodDialogVisible.value = false;
    currentGoodData.goodRemark = ""
    currentGoodData.goodScore = ""
  } else {
    ElMessage({
      type: 'info',
      message: '设置失败',
    });
  }
}

const scoreInput = ref(null);
const handleScore = async (row, type) => {
  dialogVisible.value = true
  currentData.title = row.product_name + " " + type + "部分"
  currentData.id = row.id
  currentData.type = type
  score.value = row.my_score
  score_remark.value = row.my_score_remark
  //自动对焦到input上
  watch(dialogVisible, (newVal) => {
    if (newVal) {
      nextTick(() => {
        if (scoreInput.value) {
          scoreInput.value.focus();
        }
      });
    }
  });
};

const goodRemarkInput = ref(null);
const goodScoreInput = ref(null);
const handleGoodPaper = async (row, type) => {
  goodDialogVisible.value = true
  currentGoodData.title = row.product_name + "（" + row.member + "）"
  currentGoodData.id = row.id
  currentGoodData.type = type
  currentGoodData.isGood = row.isGood
  currentGoodData.goodRemark = row.goodRemark
  currentGoodData.goodScore = row.goodScore

  //自动对焦到input上
  watch(goodDialogVisible, (newVal) => {
    if (newVal) {
      nextTick(() => {
        if (goodScoreInput.value) {
          goodScoreInput.value.focus();
        }
      });
    }
  });
};


const goPerson = async () => {
  router.push({
    path: '/work_score/person',
    query: { ...searchForm } // 使用 query 参数传递数据
  })
}

const goGood = async () => {
  router.push({
    path: '/work_score/good',
    query: { ...searchForm } // 使用 query 参数传递数据
  })
}

//筛选成员 begin
const filterByMemberBianji = (member) => {
  selectedMember.value = member;
  tableDataBianji.value = originalDataBianji.value.filter(item => item.member === selectedMember.value);
}
const filterByMemberSheji = (member) => {
  selectedMember.value = member;
  tableDataSheji.value = originalDataSheji.value.filter(item => item.member === selectedMember.value);
}
const filterByMemberJishu = (member) => {
  selectedMember.value = member;
  tableDataJishu.value = originalDataJishu.value.filter(item => item.member === selectedMember.value);
}
const clearFilterBianji = () => {
  selectedMember.value = '';
  tableDataBianji.value = originalDataBianji.value;
}
const clearFilterSheji = () => {
  selectedMember.value = '';
  tableDataSheji.value = originalDataSheji.value;
}
const clearFilterJishu = () => {
  selectedMember.value = '';
  tableDataJishu.value = originalDataJishu.value;
}
//筛选成员 end

const onLoadImage = (event) => {
  const img = event.target
  const isHorizontal = img.naturalWidth < img.naturalHeight

  // 直接修改图片的样式
  img.style.height = isHorizontal ? '200px' : 'auto'
  img.style.width = isHorizontal ? 'auto' : '200px'
}

const formatRemark = (remark) => {
  if (!remark) return '';

  // 正则表达式匹配 URL
  const urlPattern = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;

  // 将 URL 替换为超链接并替换换行符为 <br>
  return remark
    .replace(urlPattern, (url) => `<a href="${url}" target="_blank">${url}</a>`)
    .replace(/\n/g, '<br>');
};



const tableBianjiRowClassName = ({
  row,
  rowIndex,
}) => {
  if (row.isGood) {
    return 'warning-row'
  }
  return ''
}

const tableShejiRowClassName = ({
  row,
  rowIndex,
}) => {
  if (row.isGood) {
    return 'warning-row'
  }
  return ''
}

const tableJishuRowClassName = ({
  row,
  rowIndex,
}) => {
  if (row.isGood) {
    return 'warning-row'
  }
  return ''
}

const scoreCache = ref(new Map()) // 用于存储已经请求过的 big_id 及其分数
// 获取并处理项目名称（带分数）
const processRowData = async (row) => {
  if (row.big_id !== null) {
      try {
        const res = await workApi.getRestScore({ id: row.big_id, scorer: username });
        if (res.data != null && res.data != "") {
          const score = res.data;
          row.displayName = `${row.product_name}<span style="color: red;">（剩余 ${score} 分）</span>`;
        } else {
          row.displayName = row.product_name; // 没有分数时
        }
      } catch (error) {
        console.error("Error fetching score:", error);
        row.displayName = row.product_name; // 出错时
      }
  } else {
    row.displayName = row.product_name; // big_id 为空时
  }
};

// 初始化数据：处理表格中每一行
const initializeTableDataSheji = async () => {
  for (const row of tableDataSheji.value) {
    await processRowData(row);
  }
};

// 当表格数据变化时，重新处理
watch(
  tableDataSheji,
  async (newData) => {
    // 使用 Promise.all 来并行处理所有行数据
    await Promise.all(newData.map(row => processRowData(row)));
  },
  { immediate: true, deep: true }
);


</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  width: 100%;
  height: 100%;
}

.el-tag {
  margin: 5px 5px 5px 0;
}

.el-tab {
  margin: 20px 10px;
}

.files-wrapper {
  display: flex;
  flex-wrap: wrap;
  /* 允许换行 */
  align-items: flex-start;
  /* 确保所有项在交叉轴（垂直方向）上对齐 */
}

.file-container {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  position: relative;
  width: 200px;
  height: 200px;
  overflow: hidden;
  /* 防止图片超出容器 */
  border: 1px solid #dcdcdc;
  /* 可以根据需要添加边框 */
  border-radius: 8px;
  /* 圆角效果 */
  background-color: #f9f9f9;
  /* 背景颜色 */
  margin: 8px;
}

.file-container .image,
.file-container .video {
  transition: transform 0.3s linear;
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
}

.file-container:hover .image,
.file-container:hover .doc,
.file-container:hover .video {
  transform: scale(1.05);
}

.file-container .video {
  width: 100%;
  /* 确保视频宽度填满容器 */
  height: auto;
  /* 让高度自适应 */
}



.doc {
  width: 150px;
  height: 150px;
  border: 1px solid #9bb0e0;
  margin: 0 10px;
  padding: 10px;
  word-wrap: break-word;
  word-break: break-all;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  background: linear-gradient(135deg, #f6f8fc, #e9eef9);
  transition: transform 0.3s linear;
}

.doc span {
  display: inline-block;
  vertical-align: middle;
  padding: 0 10px;
  width: 60%;
  overflow: hidden;
  white-space: normal;
  word-wrap: break-word;
  line-height: normal;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  text-align: center;
  color: #6a6a6b;
  font-weight: bold;
}

.members {
  margin-bottom: 20px;
}

.members .el-button {
  margin: 10px;
}

.members .el-button.active {
  background-color: #409eff;
  color: white;
}

:deep(.warning-row) {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

:deep(.success-row) {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
